package com.zyf.ui;

import com.zyf.service.*;
import com.zyf.service.ai.HandleAiBP;
import com.zyf.service.audio.HandleKugouTempBP;
import com.zyf.service.img.CuttingImgService;
import com.zyf.service.img.HandleImageMergeService;
import com.zyf.service.img.ImageHandle;
import com.zyf.service.listener.FileChooserListener;
import com.zyf.utils.PublicEnums;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

public class ImgHandleWindow extends JFrame  {

    private static String resultStr;
    private static StringBuffer imgFolderBuffer = new StringBuffer("null");
    private static JTextField textFieldsize = new JTextField();
    private static StringBuffer txtBuffer = new StringBuffer("null");
    private static StringBuffer txtFolderBuffer = new StringBuffer("null");
    private static JComboBox actionType = new JComboBox();// 业务选择

    private static JLabel label = new JLabel();

    private static final int WIDTH = 420;
    private static final int HEIGHT = 25;

    private static final int BTNWIDTH = 100;
    private static final int BTNHEIGHT = 50;

    private static final int BTNSTARTY = 300;

    private static final int LABELWIDTH = 290;
    private static final int LABELHEIGHT = 25;
    private static final int LABELSTARTX = 50;
    private static final int LABELSTARTY = 50;

    private static final int FONTHEIGHT = 25;
    private static final int SCREENWIDTH = 920;
    private static final int SCREEHEIGHT = 500;

    public ImgHandleWindow() {
        //窗体名称
        this.setTitle("图片处理");
        //窗体大小（具体值跟电脑显示器的像素有关，可调整到合适大小）
        this.setSize(SCREENWIDTH, SCREEHEIGHT);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置退出进程的方法
        this.setDefaultCloseOperation(3);
        //设置居中显示用3
        this.setLocationRelativeTo(null);
        //流式布局管理器:给窗体设置为流式布局——从左到右然后从上到下排列自己写的组件顺序
        this.setLayout(null);//自定义设置

        //标签
        JLabel jla = new JLabel("请选择要进行的业务:");
        //设置大小
        jla.setBounds(LABELSTARTX, LABELSTARTY, LABELWIDTH, LABELHEIGHT);
        jla.setFont(new Font("楷体", Font.BOLD, FONTHEIGHT));
        jla.setBackground(Color.MAGENTA);
        this.add(jla);//将组件加到窗体上

        //添加开始按钮
        JButton jbu = new JButton("开始");
        jbu.setFont(new Font("楷体", Font.BOLD, FONTHEIGHT));
        Color color = new Color(28, 144, 62, 255);
        jbu.setForeground(color);
        //添加一个监听器,给按钮添加动作监听器方法
        jbu.addActionListener(new ButtonListener(jbu));
        jbu.setBounds((SCREENWIDTH - BTNWIDTH) / 2, BTNSTARTY, BTNWIDTH, BTNHEIGHT);
        this.add(jbu);   //给窗体添加一个按钮对象

        //添加返回按钮
        JButton backBtn = new JButton("返回");
        backBtn.setFont(new Font("楷体", Font.BOLD, 28));
        Color colorBack = new Color(28, 144, 35, 255);
        backBtn.setForeground(colorBack);
        backBtn.addActionListener(new BackButtonListener(backBtn));
        backBtn.setBounds(0, 0, BTNWIDTH, 30);
        this.add(backBtn);   //给窗体添加一个按钮对象


        actionType.setBounds(LABELSTARTX + LABELWIDTH, LABELSTARTY, WIDTH, HEIGHT + 5);
        actionType.setFont(new Font("楷体", Font.BOLD, FONTHEIGHT));
        add(actionType);
        //创建多选框
        createServiceChooser();
        //创建文件选择框
        createFilechooser(this);
        //错误提示框
        label.setBounds((SCREENWIDTH - SCREEHEIGHT) / 2, BTNSTARTY + BTNWIDTH, SCREEHEIGHT, LABELHEIGHT);
        label.setFont(new Font("楷体", Font.BOLD, FONTHEIGHT));
        label.setForeground(Color.RED);
        this.add(label);
        //设置背景图片,创建一个JLabel并设置图片
        InputStream inputstream = null;
        ByteArrayOutputStream byteArrayInputStream =null;
        try {
            inputstream = this.getClass().getClassLoader().getResourceAsStream("back.jpg");
            // 创建ByteArrayOutputStream
             byteArrayInputStream = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[1024]; // 缓冲区大小为1024字节
            // 读取InputStream并写入ByteArrayOutputStream
            while ((nRead = inputstream.read(data, 0, data.length)) != -1) {
                byteArrayInputStream.write(data, 0, nRead);
            }
            // 将收集的数据转换为字节数组
            byte[] byteArray = byteArrayInputStream.toByteArray();
            JLabel background = new JLabel(new ImageIcon(byteArray));
            background.setOpaque(true); // 设置为不透明
            background.setLayout(null); // 设置布局管理器为null
            // 设置JLabel的大小与JFrame相同
            background.setBounds(0, 0, this.getWidth(), this.getHeight());
            this.add(background);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputstream!=null){
                    inputstream.close();
                }
                byteArrayInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        this.setVisible(true);   //设置可见，放在代码最后一句

    }

    /**
     * 返回按钮监听器
     */
    class BackButtonListener implements ActionListener {
        private JButton button;

        public BackButtonListener(JButton button) {
            this.button = button;
        }

        public void actionPerformed(ActionEvent e) {
            DrawingWindowService.createUI(PublicEnums.WindowsType.ServiceWindow.getValue());
        }
    }


    private void createServiceChooser() {
        InputStream inputstream = this.getClass().getClassLoader().getResourceAsStream("configuration.txt");
        BufferedReader reader = null;
        String temp = "";
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            while ((temp = reader.readLine()) != null) {
                if (temp.startsWith("imghandletype")) {
                    this.actionType.addItem(temp.substring(temp.indexOf("=") + 1).trim());
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();

            if (reader != null)
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 业务类型选择(单选)
     */
    private static void actionType(JFrame jf) {

//        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        jf.setBounds(200, 200, 150, 300);
//        jf.setResizable(false);
//        JPanel jp = new JPanel();
        JRadioButton radio1 = new JRadioButton("1:批量裁剪图片");
        radio1.addActionListener(new RadioButtonListener(radio1));//添加监听器

        JRadioButton radio2 = new JRadioButton("2:图片批量添加文字");
        radio2.addActionListener(new RadioButtonListener(radio2));//添加监听器

        JRadioButton radio3 = new JRadioButton("3:批量裁剪图片同时添加文字");
        radio3.addActionListener(new RadioButtonListener(radio3));//添加监听器

        JRadioButton radio4 = new JRadioButton("4:批量单张图片合成单个视频(可添加音频)");
        radio4.addActionListener(new RadioButtonListener(radio4));//添加监听器

        JRadioButton radio5 = new JRadioButton("5:多张图片合成单个视频(可添加音频)");
        radio5.addActionListener(new RadioButtonListener(radio5));//添加监听器

        JRadioButton radio6 = new JRadioButton("6:批量裁剪图片并添加文字,同时批量合成单个视频(可添加音频)");
        radio6.addActionListener(new RadioButtonListener(radio6));//添加监听器

        JRadioButton radio7 = new JRadioButton("7:单张视频大片(可添加音频)");
        radio7.addActionListener(new RadioButtonListener(radio7));//添加监听器

        JRadioButton[] jrba = {radio1, radio2, radio3, radio4, radio5, radio6, radio7};
        ButtonGroup bg = new ButtonGroup();
        for (int i = 0; i < 7; i++) {
            jrba[i].setBounds(50, 80 + 40 * i, 900, 40);
            jrba[i].setFont(new Font("楷体", Font.BOLD, 25));//设置字体
            jrba[i].setIconTextGap(5);//设置图标文字间距
            jf.add(jrba[i]);//添加单选框到窗体
            bg.add(jrba[i]);//添加单选框到组件组
        }
        radio1.setSelected(true);
    }

    /**
     * 单选框监听器
     */
    static class RadioButtonListener implements ActionListener {
        private JRadioButton radioButton;

        public RadioButtonListener(JRadioButton radioButton) {
            this.radioButton = radioButton;
        }

        public void actionPerformed(ActionEvent e) {
            //检测到按钮被点击自动计入到这个函数，这个函数是ActionListener类的方法
            if (radioButton.isSelected()) {
                resultStr = radioButton.getText();
                System.out.println(resultStr);
            }
        }
    }

    /**
     * 开始按钮监听器
     */
    static class ButtonListener implements ActionListener {
        private JButton button;

        public ButtonListener(JButton button) {
            this.button = button;
        }

        public void actionPerformed(ActionEvent e) {
            int windowType= ImgHandleWindow.actionType.getSelectedIndex()+1;
            String message ="";
            switch (windowType) {
                case 1://批量裁剪图片
                    label.setVisible(false);
                    if (imgFolderBuffer.toString().equals("null")) {
                        label.setText("请选择图片文件夹!");
                        label.setVisible(true);
                        return;
                    }
                    message = CuttingImgService.ImgCutBatch(imgFolderBuffer.toString(),0,60);
                    break;
                case 2://图片批量添加文字
                    label.setVisible(false);
                    if (imgFolderBuffer.toString().equals("null")) {
                        label.setText("请选择图片文件夹!");
                        label.setVisible(true);
                        return;
                    }
                    if (imgFolderBuffer.toString().contains(".")) {
                        label.setText("请选文件夹类型!");
                        label.setVisible(true);
                        return;
                    }
                    if (txtBuffer.toString().equals("null")) {
                        label.setText("请选择文档!");
                        label.setVisible(true);
                        return;
                    }
                    if (!txtBuffer.toString().endsWith(".txt")) {
                        label.setText("请选文档类型!");
                        label.setVisible(true);
                        return;
                    }
                    message = MergeDataService.writeTxt2Img(imgFolderBuffer.toString(), txtBuffer.toString());//批量添加文字
                    break;
                case 3:
                    if (imgFolderBuffer.toString().equals("null")) {
                        label.setText("请选择图片文件夹!");
                        label.setVisible(true);
                        return;
                    }
                    if (textFieldsize.getText() == null || textFieldsize.getText().equals("")) {
                        label.setText("请输入要调整的图片尺寸!");
                        label.setVisible(true);
                        return;
                    }
                    try {
                        String sizestr = textFieldsize.getText();
                        String[] size=sizestr.split("X").length==2?sizestr.split("X"):sizestr.split("x");
                        ImageHandle.resizeImage(imgFolderBuffer.toString(), Integer.valueOf(size[0]), Integer.valueOf(size[1]));
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                case 4://下载图片
                    if (txtBuffer.toString().equals("null")) {
                        label.setText("请选择文档!");
                        label.setVisible(true);
                        return ;
                    }
                    if (textFieldsize.getText() == null || textFieldsize.getText().equals("")) {
                        label.setText("请输入光标位置！");
                        label.setVisible(true);
                        return;
                    }
                    try {
                        new HandleAiBP().uploadFiles(txtBuffer.toString(),textFieldsize.getText());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                case 5:
                    break;
                case 6:
                    label.setVisible(false);
                    if (imgFolderBuffer.toString().equals("null")) {
                        label.setText("请选择图片文件夹!");
                        label.setVisible(true);
                        return ;
                    }
                    if (imgFolderBuffer.toString().contains(".")) {
                        label.setText("请选文件夹类型!");
                        label.setVisible(true);
                        return ;
                    }
                    if (txtBuffer.toString().equals("null")) {
                        label.setText("请选择文档!");
                        label.setVisible(true);
                        return ;
                    }
                    if (!txtBuffer.toString().endsWith(".txt")) {
                        label.setText("请选文档类型!");
                        label.setVisible(true);
                        return ;
                    }
                    message = MergeDataService.writeLongTxt2Img(imgFolderBuffer.toString(), txtBuffer.toString());
                    break;
                case 7://生成一张书签图片
                    label.setVisible(false);
                    if (txtBuffer.toString().equals("null")) {
                        label.setText("请选择文档!");
                        label.setVisible(true);
                        return ;
                    }

                    HandleImageMergeService service=new HandleImageMergeService();
                    try {
                        message = service.mergeSingleText2Image(txtBuffer.toString());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                case 8://生成封面图片
                    label.setVisible(false);
                    if (txtBuffer.toString().equals("null")) {
                        label.setText("请选择文档!");
                        label.setVisible(true);
                        return ;
                    }
                    if (imgFolderBuffer.toString().equals("null")) {
                        label.setText("请选择图片文件夹!");
                        label.setVisible(true);
                        return;
                    }
                    try {
                        message = new HandleImageMergeService().createCoverImg(txtBuffer.toString(),imgFolderBuffer.toString(),100);
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                case 9://批量修改文件名
                    label.setVisible(false);
                    if (imgFolderBuffer.toString().equals("null")) {
                        label.setText("请选择图片文件夹!");
                        label.setVisible(true);
                        return;
                    }
                    try {
                         new HandleFileService().renameFile(imgFolderBuffer.toString());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                case 10://批量整理诗词(换行,加作者,去符号)
                    label.setVisible(false);
//                    if (imgFolderBuffer.toString().equals("null")) {
//                        label.setText("请选择文本文件夹!");
//                        label.setVisible(true);
//                        return;
//                    }
//                    try {
//                        new HandleTxtService().handleTxt(imgFolderBuffer.toString());
//                    } catch (Exception ex) {
//                        throw new RuntimeException(ex);
//                    }
                    break;
                case 11://酷狗音乐缓存文件转换为mp3
                    label.setVisible(false);
                    if (imgFolderBuffer.toString().equals("null")) {
                        label.setText("请选择音乐缓存文件夹!");
                        label.setVisible(true);
                        return;
                    }
                    if (txtBuffer.toString().equals("null")) {
                        label.setText("请选择转换程序.exe");
                        label.setVisible(true);
                        return;
                    }
                    try {
                        new HandleKugouTempBP().handleKugouMusic(imgFolderBuffer.toString(),txtBuffer.toString());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                case 12://根据歌曲名重命名文件
                    label.setVisible(false);
                    if (imgFolderBuffer.toString().equals("null")) {
                        label.setText("请选择音乐缓存文件夹!");
                        label.setVisible(true);
                        return;
                    }
                    try {
                        new HandleKugouTempBP().handleMusicName(imgFolderBuffer.toString());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                case 13://获取古诗词前四行
                    label.setVisible(false);
                    if (imgFolderBuffer.toString().equals("null")) {
                        label.setText("请选择文件夹!");
                        label.setVisible(true);
                        return;
                    }
                    try {
                        new HandleTxtService().handleBeforeFourLines(imgFolderBuffer.toString(),7);
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                case 14://电子书epub 转txt
                    label.setVisible(false);
                    if (imgFolderBuffer.toString().equals("null")) {
                        label.setText("请选择文件夹!");
                        label.setVisible(true);
                        return;
                    }
                    try {
                        new HandleTxtService().handleEpubToTxt(imgFolderBuffer.toString());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                default:
                    break;
            }

        }
    }

    /**
     * 创建文件选择框
     *
     * @param jf
     */
    private static void createFilechooser(JFrame jf) {
        int interval = 40;//选择框间隔
        int chooserHeight = 30;
        String txt = "请选择图片文件夹:";
        for (int i = 0; i < 3; i++) {
            JTextField textField = new JTextField();// 文本域
            JButton btn = new JButton("浏览");// 钮1
            textField.setBounds(LABELSTARTX + LABELWIDTH, LABELSTARTY + interval * (i + 1), WIDTH, chooserHeight);
            btn.setBounds(LABELSTARTX + LABELWIDTH + WIDTH, LABELSTARTY + interval * (i + 1), BTNWIDTH, chooserHeight);
            if (i == 0) {
                btn.addActionListener(new FileChooserListener(textField, imgFolderBuffer, PublicEnums.FilechooseType.OnlyDerectory.getValue()));
            }
            if (i == 1) {
                btn.addActionListener(new FileChooserListener(textField, txtBuffer, PublicEnums.FilechooseType.OnlyFile.getValue()));
                txt = "请选择txt文件:";
            }
            if (i == 2) {
                textFieldsize = textField;
                btn.setText("例:90X100");
                txt = "输入图片要调整的尺寸:";
            }
            JLabel label = new JLabel(txt);// 标签
            label.setFont(new Font("楷体", Font.BOLD, FONTHEIGHT));
            label.setBounds(LABELSTARTX, LABELSTARTY + interval * (i + 1), LABELWIDTH, LABELHEIGHT);
            // 设置布局
            jf.add(label);
            jf.add(textField);
            jf.add(textFieldsize);
            jf.add(btn);
        }
    }


}
